<?php


namespace App\Admin\Override;

use App\Utils\Helper;
use Dcat\Admin\Admin;
use Dcat\Admin\Show as Base;


class Show extends Base
{
    public function __construct($id = null, $model = null, \Closure $builder = null)
    {
        parent::__construct($id, $model, $builder);
        //判断是api还是后台
        if(Admin::user()){
            $this->disableListButton();
            $this->disableQuickEdit()
                ->disableEditButton(
                    Admin::user()->cannot(Helper::resolvePermissionRouteName('update'))
                )
                ->disableDeleteButton(
                    Admin::user()->cannot(Helper::resolvePermissionRouteName('destroy'))
                )->disableEditButton()->disableDeleteButton();
        }
    }

    public function disableHeader(): Show
    {
        $this->disableDeleteButton();
        $this->disableEditButton();
        $this->disableListButton();
        $this->panel->title('');

        return $this;
    }

    public function field($name, $label = '')
    {
        if ($name == 'id' && $label == '') {
            $label = trans('common.id');
        }
        return parent::field($name, $label);
    }

    /**
     * @param string $field
     */
    public function disableButtonOnMaintenance(string $field)
    {
        if (Maintenance::isNotMaintenance($field)) {
            $this->disableEditButton()
                ->disableQuickEdit()
                ->disableDeleteButton();
        }
    }

    /**
     * @param string $field
     * @param string|array|null $path when path is null, will use $show->model()->$field
     * @param string $label
     */
    public function fileDetail(
        string            $field = 'files',
        string|array|null $path = null,
        string            $label = '',
        string            $name  = '',
        bool              $read = true,
        bool              $download = true,
        int               $type = 1
    )
    {
        if(!$path && !is_array($this->model()->$field)) $path =  explode(',',$this->model()->$field??'');
        if(!is_array($path)){
            $path = explode(',',$path);
        }
        $path = array_filter((array)($path ?? $this->model()->$field ?? []));

        $html = Helper::filePreviewHtmlData($path,$name,$read,$download,$type);
        $label = $this->formatLabels($field,$label);
        $this->html(view('audits/audit_file_new',['data'=>$html,'label'=>$label]));
//        $html = Helper::filePreviewHtml($path,$name,$read,$download);
//        $this->field($field, $label)
//            ->unescape()
//            ->as(function () use ($html) {
//                return $html;
//            });
    }

    protected function formatLabels($field,$label)
    {
        if ($label) {
            return $label;
        }

        $label = admin_trans_field($field);

        return str_replace('_', ' ', $label);
    }
}
